<template>
  <div
    class="container w-full h-full flex"
    v-if="currentQuestion && !currentQuestion.answerScoreable"
  >
    <div class="left h-full bg-white flex-1 p-20px box-border overflow-hidden">
      <div ref="scroll" class="w-full h-full overflow-scroll">
        <Stem :data="stem" />
        <!-- 对答案 -->
        <div class="mt-100px" v-if="!isShowAnalysis">
          <div class="flex justify-center">
            <CustomButton
              class="block"
              style="width: 2rem"
              @click="checkAnswer(0)"
              @long-press="checkAnswer(1)"
              >对答案
            </CustomButton>
            <CustomButton class="block ml-60px" style="width: 2rem" @click="skip"
              >跳过，下一题
            </CustomButton>
          </div>

          <!-- 作答说明 -->
          <div class="mt-10">
            <div class="module-item flex text-333 font-medium mt-20px mb-12px">
              <div class="rect mr-6px"></div>
              <div class="">作答说明</div>
            </div>
            <div class="description p-20px bg-F4F7FB text-666666">
              <div>1.点击对答案后需上传作答过程；</div>
              <div>2.你也可以长按对答案，直接显示答案；</div>
              <div>3.直接对答案或者跳过题目，都不被计入每日打卡的有效做题</div>
            </div>
          </div>
        </div>

        <!-- 答案和解析 -->
        <div class="mt-10" v-else>
          <div
            class="module-item flex text-333 font-medium mt-20px mb-12px"
            v-show="studentAnswerUrl"
          >
            <div class="rect mr-6px"></div>
            <div class="">作答过程</div>
          </div>
          <div style="font-size: 0" v-show="studentAnswerUrl">
            <el-image
              style="width: 0.8rem; height: auto"
              :src="studentAnswerUrl"
              :preview-src-list="[studentAnswerUrl]"
            />
          </div>
          <!-- answer -->
          <!-- <div class="module-item flex text-333 font-medium mt-20px mb-12px">
            <div class="rect mr-6px"></div>
            <div class="">答案</div>
          </div>
          <div
            class="answer p-20px bg-F4F7FB text-333"
            style="white-space: break-spaces; word-break: break-all"
            v-html="answerHtml"
          ></div> -->
          <!-- explanation -->
          <div class="module-item flex text-333 font-medium mt-20px mb-12px">
            <div class="rect mr-6px"></div>
            <div class="">解析</div>
          </div>
          <div
            class="explanation p-20px bg-F4F7FB text-333"
            style="white-space: break-spaces; word-break: break-all"
            v-html="explanationHtml"
          ></div>
        </div>
      </div>
    </div>
    <div
      class="right h-full bg-white p-20px box-border ml-20px flex flex-col"
      style="font-size: 0.14rem"
    >
      <div class="flex-1"></div>
      <div class="footer box-border">
        <div class="selectTarget" v-show="isShowAnalysis">
          <div class="child">
            <img src="@/assets/exercise/answertrue@2x.png" alt="" @click="onStatusChange(1)" />
            <span>我做对了</span>
          </div>
          <div class="child">
            <img src="@/assets/exercise/answerfalse@2x.png" alt="" @click="onStatusChange(2)" />
            <span>我做错了</span>
          </div>
        </div>
        <div class="item-auto" v-show="isShowAnalysis">
          <img
            v-show="isAddWqBook"
            src="@/assets/exercise/seed@2x.png"
            alt=""
            @click="onIsAddWqBookChange(false)"
            class="mr-6px"
          />
          <img
            v-show="!isAddWqBook"
            src="@/assets/exercise/crile@2x.png"
            alt=""
            class="mr-6px"
            @click="onIsAddWqBookChange(true)"
          />
          <span>将该题加入错题本</span>
        </div>
        <div class="flex flex-col items-center">
          <CustomButton
            class="block"
            style="width: 2rem"
            @click="prevQuestion"
            v-show="isShowPrevBtn"
            >上一题
          </CustomButton>

          <CustomButton
            :class="['block', isShowPrevBtn ? 'mt-20px' : '']"
            style="width: 2rem"
            :style="
              hasMoreQuestion || questionIndex != questions.length - 1 ? '' : 'background:#DCDCDC'
            "
            @click="nextQuestion"
            v-show="isShowNextBtn"
            >下一题
          </CustomButton>
        </div>
      </div>
    </div>
    <!-- 退出练习弹窗 -->
    <div class="quit-practice-dialog-wrap" v-show="isShowQuitPracticeDialog">
      <div class="quit-practice-dialog bg-white px-24px py-30px relative flex flex-col">
        <div class="header relative w-full flex justify-center items-center text-white">
          <img
            class="close absolute"
            src="static/icons/close.png"
            mode=""
            @click="isShowQuitPracticeDialog = false"
          />
          <div class="title font-medium text-262A30">提示</div>
        </div>
        <div class="main text-A3A3A3 py-30px flex-center flex-1"> 请先选择是否做对？ </div>
        <div class="footer flex justify-center">
          <CustomButton class="block" style="width: 2rem" @click="isShowQuitPracticeDialog = false"
            >好的</CustomButton
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Stem from '@/components/question/exercise/stem/index'
import CustomButton from '@/components/button'
import { uploadImage } from '@/utils'
import { formatQuestionStem, formatQuestionAnswer } from '@/utils/question'
import { getListCompleteByIdsApi } from '@/api/exercise'

export default {
  components: {
    Stem,
    CustomButton
  },
  props: {
    questions: {
      type: Array,
      default: () => {
        return []
      }
    },
    questionIndex: {
      type: Number,
      default: 0
    },
    hasMoreQuestion: {
      type: Boolean,
      default: false
    }
  },

  data() {
    return {
      isShowQuitPracticeDialog: false,
      isShowAnalysis: false, // 是否显示答案解析
      studentAnswerUrl: '', // 学生拍照上传的答案
      status: 0, // 答题状态： 0 => 未作答 1 => 做对了 2 => 做错了
      isAddWqBook: false // 是否加入错题本
    }
  },
  computed: {
    currentQuestionIndex() {
      return this.questionIndex
    },
    currentQuestion() {
      return this.questions[this.questionIndex]
    },
    stem() {
      const {
        stem: stemString,
        question: { stem },
        typeName
      } = this.currentQuestion

      const { type = '未知题型' } = stem ? stem : {}

      return formatQuestionStem(stemString, {
        label: typeName,
        type
      })
    },
    answer() {
      const { answer } = this.currentQuestion

      return answer.replace(/<p/g, '<p class="paragraph"')
    },
    answerHtml() {
      const { answer } = this.currentQuestion

      return answer
    },
    explanationHtml() {
      const { explanation } = this.currentQuestion

      if (!explanation)
        return '<div class="qml-explanation"><p class="paragraph" style=""><span>无</span></p></div>'

      return explanation.replace(/<p/g, '<p class="paragraph"')
    },
    // 是否显示上一题按钮
    isShowPrevBtn() {
      return this.questionIndex != 0
    },
    // 是否显示下一题按钮
    isShowNextBtn() {
      return this.isShowAnalysis
    }
  },
  watch: {
    // 切换上一题/下一题，初始化答题状态/从缓存中读取答题状态
    questionIndex() {
      this.$refs.scroll && this.$refs.scroll.scrollTo(0, 0)
      const { temp } = this.currentQuestion

      if (!temp) {
        this.isShowAnalysis = false
        this.studentAnswerUrl = ''
        this.status = 0
        this.isAddWqBook = false
      } else {
        this.isShowAnalysis = temp['isShowAnalysis']
        this.studentAnswerUrl = temp['studentAnswerUrl']
        this.status = temp['status']
        this.isAddWqBook = temp['isAddWqBook']
      }
    }
  },
  methods: {
    // 更新当前题目（菁优网）
    updateCurrentQuestion() {
      return new Promise(async (resolve) => {
        const { questionId } = this.currentQuestion
        // 获取题目详情
        const loading = this.$loading({
          lock: true,
          text: '正在获取解析...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.5)'
        })
        // 一分钟内上传不成功关闭loading弹窗
        const timer = setTimeout(() => {
          loading.close()
        }, 60000)
        const { data: questionSource, msg } = await getListCompleteByIdsApi({
          ids: questionId
        })
        clearTimeout(timer)
        loading.close()

        if (questionSource) {
          const { displayAnswer, explanation, method, discuss } = questionSource[0]
          // 更新答案
          this.currentQuestion.answer = `<div class=\"qml-answer\" data-copyright=\"jyeoo.com\"><span class=\"qml-an-sq\"><span class=\"qml-an\"><span>${displayAnswer}</span></span></span></div>`
          // 更新解析
          this.currentQuestion.explanation = `<div class=\"qml-explanation\" style=\"line-height: 0.28rem;\" data-copyright=\"jyeoo.com\"><div class=\"qml-seg\" seg-name=\"详解\">【分析】<div style=\"\">${explanation}</div></div><div class=\"qml-seg\" seg-name=\"解答\">【解答】<div style=\"\">${method}</div></div><div class=\"qml-seg\" seg-name=\"点评\">【点评】<div style=\"\">${discuss}</div></div></div>`
          this.currentQuestion.infoFlag = 1
        } else {
          this.$message.error(`获取题目解析失败，msg：${msg}`)
        }
        resolve()
      })
    },
    // 答题状态改变
    onStatusChange(value) {
      this.status = value

      switch (value) {
        case 1:
          this.isAddWqBook = false // 做对了，不加入错题本
          break
        case 2:
          this.isAddWqBook = true // 做错了，加入错题本
          break
        default:
          break
      }

      this.submit() // 提交
    },
    // 是否加入错题本状态改变
    onIsAddWqBookChange(value) {
      this.isAddWqBook = value

      // 未提交答案
      if (this.status === 0) {
        return
      }

      this.submit() // 提交
    },
    // 对答案
    async checkAnswer(type) {
      switch (type) {
        case 0:
          // 短按
          const { android_call } = window

          if (!android_call) {
            const base64 = await uploadImage()
            this.studentAnswerUrl = base64
            // 显示答案解析
            // 菁优网获取题目解析
            if (this.currentQuestion.sourceType === '3' && !this.currentQuestion.infoFlag) {
              await this.updateCurrentQuestion()
            }
            this.isShowAnalysis = true
          } else {
            const callback = async (base64) => {
              this.studentAnswerUrl = 'data:image/png;base64,' + base64
              // 显示答案解析
              // 菁优网获取题目解析
              if (this.currentQuestion.sourceType === '3' && !this.currentQuestion.infoFlag) {
                await this.updateCurrentQuestion()
              }
              this.isShowAnalysis = true
              this.$message.success('上传成功！')
            }

            const callBackName = `fn${new Date().getTime()}`
            window.android_call[callBackName] = callback.bind(this)

            android.takePhoto(callBackName)
          }
          break
        case 1:
          // 长按
          this.$popup.show({
            type: 'confirm',
            success: (popup) => {
              popup.$on('cancel', () => {
                this.$popup.hide('confirm')
              })
              popup.$on('confirm', async () => {
                this.$popup.hide('confirm')
                // 显示答案解析
                // 菁优网获取题目解析
                if (this.currentQuestion.sourceType === '3' && !this.currentQuestion.infoFlag) {
                  await this.updateCurrentQuestion()
                }
                this.isShowAnalysis = true
              })
              popup.setData({
                content: '是否不提交作答，直接对答案？',
                confirmText: '是',
                cancelText: '否'
              })
            }
          })
          break
        default:
          break
      }
    },
    skip() {
      this.$emit('next', {
        overwrite: true
      })
    },
    submit() {
      const {
        questionId,
        question: {
          stem: { type: questionType },
          answer
        },
        answerScoreable
      } = this.currentQuestion

      const data = {
        questionId, // 问题id
        questionSort: this.questionIndex + 1, // 题目序号
        questionType, // 题型
        answerScoreable, // 是否支持机阅
        questionAnswer: JSON.stringify(answer), // 题目答案
        studentAnswer: '', // 学生答案
        studentAnswerUrl: this.studentAnswerUrl, // 学生作答图片
        correct: this.status === 1 ? 0 : 1, // 是否做对 0 对 1 错
        errors: this.isAddWqBook ? 0 : 1 // 是否加入错题本 0 加 1 不加
      }

      this.$emit('submit', data)

      // 缓存答题状态
      if (!this.currentQuestion.temp) {
        this.currentQuestion.temp = {
          isShowAnalysis: this.isShowAnalysis,
          studentAnswerUrl: this.studentAnswerUrl,
          status: this.status,
          isAddWqBook: this.isAddWqBook
        }
      }
    },
    prevQuestion() {
      // 未提交答案
      if (this.isShowAnalysis && this.status === 0) {
        this.isShowQuitPracticeDialog = true
        return
      }

      this.$emit('prev')
    },
    nextQuestion() {
      // 没有下一题
      if (!this.hasMoreQuestion && this.questionIndex === this.questions.length - 1) {
        return
      }

      // 未提交答案
      if (this.status === 0) {
        this.isShowQuitPracticeDialog = true
        return
      }

      this.$emit('next')
    }
  }
}
</script>

<style lang="scss" scoped>
.quit-practice-dialog-wrap {
  width: 100vw;
  height: 100vh;
  background: rgba($color: #000000, $alpha: 0.5);
  position: absolute;
  left: 0;
  top: 0;
  z-index: 1999;

  .quit-practice-dialog {
    width: 348px;
    min-height: 158px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    border-radius: 16px;
    border: 1px solid #707070;

    .header {
      .close {
        width: 16px;
        height: 16px;
        top: -12px;
        right: -8px;
      }

      .title {
        font-size: 26px;
        line-height: 30px;
      }
    }

    .main {
      font-size: 26px;
      line-height: 28px;
    }

    .footer {
    }
  }
}
.item-auto {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 12px;
  flex-wrap: nowrap;
  img {
    width: 30px;
    height: 30px;
  }
  span {
    font-size: 26px;
    white-space: nowrap;
  }
}
.selectTarget {
  display: flex;
  align-items: center;
  justify-content: space-evenly;
  margin-bottom: 56px;
  flex-wrap: nowrap;
  .child {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    img {
      margin-bottom: 14px;
      width: 60px;
      height: 60px;
    }
    span {
      font-size: 22px;
      color: #666666ff;
      white-space: nowrap;
    }
  }
}
.container {
  .left {
    border-radius: 16px;

    .module-item {
      font-size: 26px;
      line-height: 26px;

      .rect {
        width: 4px;
        height: 26px;
        background: linear-gradient(180deg, #51c3ff 0%, #31b3f7 100%);
        border-radius: 3px;
      }
    }

    .description {
      border-radius: 8px;
      font-size: 26px;
      line-height: 28px;
    }

    .answer,
    .explanation {
      font-size: 26px;
      line-height: 26px;
      border-radius: 8px;
    }
  }

  .right {
    border-radius: 16px;
    width: 303px;

    .footer {
      height: auto;
    }

    .u-radio {
      font-size: 26px;
    }

    /deep/ .u-checkbox-label--left {
      span {
        font-size: 26px;
        color: #333;
      }

      .u-checkbox__icon-wrap--square span {
        color: #fff;
      }
    }
  }
}

/deep/ .el-radio {
  display: flex;
  align-items: center;

  &:not(:last-child) {
    margin-bottom: 0;
  }

  .el-radio__input {
    display: flex;
    align-items: center;
  }

  .el-radio__inner {
    width: 26px;
    height: 26px;
  }

  .el-radio__label {
    font-size: 26px;
    color: #333;
  }
}

/deep/ .el-checkbox {
  display: flex;
  align-items: center;
}

/deep/ .el-checkbox__label {
  font-size: 26px;
  color: #333;
}

/deep/ .el-checkbox__inner {
  width: 19px;
  height: 19px;
}

/deep/ .el-checkbox__input.is-checked + .el-checkbox__label {
  color: #333;
}

/deep/ .el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: #51c3ff !important;
  border-color: #51c3ff;
}

/deep/ .el-checkbox__inner::after {
  left: 40%;
  top: 20%;
}

/deep/ .el-checkbox__input {
  height: 19px;
}
</style>
